//
//  QueryController.m
//  MClient
//
//  Created by  史正烨 on 09-10-24.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "QueryController.h"
#import "MClientAppDelegate.h"
#import "ListController.h"
#import "MCFunction.h"
#import "AListController.h"
#import "ReportViewController.h"
#import "MCUIToolkit.h"
#import "DateTimeSelectView.h"
#import "MCControl.h"
#import "LookupSelectView.h"
#import "WithFormButtonsBar.h"

@interface QueryController (Private)
//DateTimeSelectView*  dateTimeSelect;
@end

@implementation QueryController
@synthesize dataObjectName;
@synthesize layoutName;
@synthesize listLayout;
@synthesize queryFilter;
@synthesize queryFirst;
@synthesize reportDefId;

#pragma mark ---- UIViewController方法 ----


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	@try {
		[super viewDidLoad];
		
		self.title = @"查询条件";//huotianjun 过滤条件改为查询条件
		
		[self leftBarButton:@"返回" withStyle:UIBarButtonItemStylePlain selector:@selector(selectCancelAction:)];
		
		WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, nWithFormButtonsBarHeight + 10)];
		withFormButtonsBar.tag = -8888;
		NSMutableDictionary *queryButton = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"查询",@"lbl",nil];
		NSMutableArray *withButtons = [[NSMutableArray alloc] initWithObjects:queryButton, nil];
		[withFormButtonsBar addWithFormButtons:withButtons buttonCol:1 delegate:self];
		self.tableview.tableFooterView = withFormButtonsBar;
		[withFormButtonsBar release];
		
		self.addHelpButton = YES;
		self.helpUrl = @"/iphone/help/chapter04-01.html";
		
		formData = [[NSMutableDictionary alloc] init];
		queryDataArray = [[NSMutableArray alloc] init];
		
		for (NSMutableDictionary *listField in [listLayout objectForKey:@"item"]) {
			NSString *queryMode = [listField objectForKey:@"qmode"];
			if (queryMode == nil || [queryMode length] == 0 || [queryMode intValue] == 0) {
				continue;
			}
						
			// 针对范围查询的特殊处理
			if ([queryMode intValue] == 3) {
				NSMutableDictionary *listFieldMin = [MCUIToolkit getObjectCopy:listField];
				NSMutableDictionary *fieldMin = [listFieldMin objectForKey:@"fld"];
				NSString *fieldNameMin = [[fieldMin objectForKey:@"name"]stringByAppendingFormat:@"_%@", @"min"];
				[fieldMin setObject:fieldNameMin forKey:@"name"];
				[queryDataArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
										   @"3",@"queryMode",
										   listFieldMin,@"item",
										   nil]];
				
				NSMutableDictionary *listFieldMax = [MCUIToolkit getObjectCopy:listField];
				NSMutableDictionary *fieldMax = [listFieldMax objectForKey:@"fld"];;
				NSString *fieldNameMax = [[fieldMax objectForKey:@"name"]stringByAppendingFormat:@"_%@", @"max"];
				[fieldMax setObject:fieldNameMax forKey:@"name"];
				[queryDataArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
										   @"4",@"queryMode",
										   listFieldMax,@"item",
										   nil]];
			}
			else {
				[queryDataArray addObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
										   queryMode,@"queryMode",
										   listField,@"item",
										   nil]];
			}
		}
		
		for (int i = 0; i < [queryFilter count]; i++) {
			NSMutableDictionary *filter = [queryFilter objectAtIndex:i];
			if ([[filter objectForKey:@"type"] intValue] == 3) {
				NSString *fld = [[filter objectForKey:@"fld"] stringByAppendingFormat:@"_%@", @"min"];
				[filter setObject:fld forKey:@"fld"];
			} else if ([[filter objectForKey:@"type"] intValue] == 4) {
				NSString *fld = [[filter objectForKey:@"fld"] stringByAppendingFormat:@"_%@", @"max"];
				[filter setObject:fld forKey:@"fld"];
			}
		}
	}
	@catch (NSException *e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];
	}
    
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[self reloadData];
}


- (void)dealloc {
	[dataObjectName release];
	[layoutName release];
	[listLayout release];
	[queryFilter release];
	[queryDataArray release];
	[formData release];
	[reportDefId release];
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [queryDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	int row = [indexPath row];
    float labelFontSize = 18.0,valueFontSize = 18.0;//huotianjun 默认16号字
	
	NSMutableDictionary *queryData = [queryDataArray objectAtIndex:row];
	NSMutableDictionary *appItem = [queryData objectForKey:@"item"];
	NSMutableDictionary *field = [appItem objectForKey:@"fld"];
	NSString *fieldName = [field objectForKey:@"name"];
	NSString *queryMode = [queryData objectForKey:@"queryMode"];

	NSString *value = @"";
	for (int i = 0; i < [queryFilter count]; i++) {
		NSMutableDictionary *filter = [queryFilter objectAtIndex:i];
		if ([fieldName isEqualToString:[filter objectForKey:@"fld"]]) {
			value = [filter objectForKey:@"value"];
			break;
		}
	}
	NSMutableDictionary *datas = [formData objectForKey:@"data"];
	if (datas == nil) {
		datas = [NSMutableDictionary dictionary];
		[formData setObject:datas forKey:@"data"];
	}
	NSMutableDictionary *fieldData = [datas objectForKey:fieldName];
	if (fieldData == nil) {
		fieldData = [NSMutableDictionary dictionary];
		[fieldData setObject:value forKey:@"value"];
		[datas setObject:fieldData forKey:fieldName];
	}
	
	UITableViewCell *cell = [MCFunction createCellForQueryForm:tableView 
													   appItem:appItem
													 indexPath:(NSIndexPath *)indexPath 
													  formView:self.clientView];
	
	UILabel *labelField = (UILabel *)[cell.contentView viewWithTag:-1];
	labelField.text = [MCUIToolkit getFieldLabel:appItem];
    labelField.font = [UIFont boldSystemFontOfSize:labelFontSize];
	if ([queryMode intValue] == 4) {
		labelField.text = @"";
	}
	
	NSString *valueText = [MCUIToolkit getFieldTextValue:formData
												 appItem:appItem
											selectOption:[formData objectForKey:@"so"]];
	NSString *fieldType = [MCUIToolkit getFieldType:appItem];
	char cFieldType;
	strncpy(&cFieldType, [fieldType UTF8String], 1);
	if (cFieldType != 'B') {
		MCControl* valueField = (MCControl *)[cell.contentView viewWithTag:-2];
        valueField.font = [UIFont boldSystemFontOfSize:valueFontSize];//huotianjun
		if (cFieldType == 'H'||cFieldType == 'I'||cFieldType == 'K'||cFieldType == 'L') {
			NSArray *selectIcons = [valueText componentsSeparatedByString:@"::"];
			if ([selectIcons count] > 1) {
				for(UIImageView *imageView in [valueField subviews]){
					[imageView removeFromSuperview];
				}
				NSString *iconLabel = [selectIcons objectAtIndex:1];
				NSArray *icons = [iconLabel componentsSeparatedByString:@","];
				for (int j = 0; j < [icons count]; j++) {
					NSString *icon = [icons objectAtIndex:j];
					UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(32 * j, 0, 24, 24)];
					imageView.image = [MCFunction scaleAndRotateImage:[UIImage imageNamed:icon] width:24.0 height:24.0];
					imageView.backgroundColor = [UIColor clearColor];
					[valueField addSubview:imageView];
					[imageView release];
				}
				return cell;
			} 
		}
		if (valueField.style == MCControl_TextField) {
			[valueField.control addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
			((UITextField*)valueField.control).delegate = self;
		}
		valueField.text = valueText;
	} else {
		UISwitch *valueField = (UISwitch *)[cell.contentView viewWithTag:-2];
		if ([valueText isEqualToString:@"☑"]) {
			valueField.on = YES;
		}else {
			valueField.on = NO;
		}
	}
	
	UILabel *modeLabel = (UILabel *)[cell.contentView viewWithTag:-3];
	switch ([queryMode intValue]) {
		case 1:
			modeLabel.text = @"等于";
			break;
		case 2:
			modeLabel.text = @"包含";
			break;
		case 3:
			modeLabel.text = @"从";
			break;
		case 4:
			modeLabel.text = @"到";
			break;
		case 5:
			modeLabel.text = @"属于";
			break;
		default:
			modeLabel.text = @"";
			break;
	}
	
	return cell;
}	

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[[self findFirstResponder] resignFirstResponder];
	
	if ([DateTimeSelectView instance].isShown) {
		[[DateTimeSelectView instance] selectCancelAction];
	}
	if ([LookupSelectView instance].isShown) {
		[[LookupSelectView instance] selectCancelAction];
	}
	
	UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
	
	int row = [indexPath row];
	
	NSMutableDictionary *queryData = [queryDataArray objectAtIndex:row];
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	
	[MCFunction selectDetailForQueryForm:self 
								withCell:cell
								 appItem:[queryData objectForKey:@"item"]
								  record:formData];
	
}

#pragma mark ---- 按钮事件处理方法 ----
- (void) withFormButtonsAction: (id) sender {
	@try {
		[[self findFirstResponder] resignFirstResponder];
		if ([DateTimeSelectView instance].isShown) {
			[[DateTimeSelectView instance] selectCancelAction];
		}
		if ([LookupSelectView instance].isShown) {
			[[LookupSelectView instance] selectCancelAction];
		}
		NSMutableArray *queryFilters = [NSMutableArray array];
		int rowNum = 0;
		for (NSMutableDictionary *queryData in queryDataArray) {
			
			NSMutableDictionary *appItem = [queryData objectForKey:@"item"];
			NSMutableDictionary *field = [appItem objectForKey:@"fld"];
			NSMutableDictionary *relField = [appItem objectForKey:@"rfld"];
			
			NSString *fieldName = [field objectForKey:@"name"];
			NSString *queryMode = [queryData objectForKey:@"queryMode"];
			NSMutableDictionary *datas = [formData objectForKey:@"data"];
			NSMutableDictionary *fieldData = [datas objectForKey:fieldName];
			
			NSString *fieldType = [MCUIToolkit getFieldType:appItem];
			if ([fieldType isEqualToString:@"B"]) {
				UITableViewCell *cell = [self.tableview cellForRowAtIndexPath:[NSIndexPath indexPathForRow:rowNum inSection:0]];
				UISwitch *valueField = (UISwitch *)[cell.contentView viewWithTag:-2];
				if (fieldData == nil) {
					fieldData = [NSMutableDictionary dictionary];
					[datas setObject:fieldData forKey:fieldName];
				}
				[fieldData setObject:valueField.on?@"1":@"0" forKey:@"value"];
			}
			
			if (fieldData != nil) {
				NSMutableDictionary *filter = [NSMutableDictionary dictionary];
				if ([queryMode intValue] == 3 || [queryMode intValue] == 4) {
					[filter setObject:[fieldName substringToIndex:[fieldName length] - 4] forKey:@"fld"];
				}else {
					[filter setObject:fieldName forKey:@"fld"];
				}
				[filter setObject:queryMode forKey:@"type"];
				NSString *value = [fieldData objectForKey:@"value"]; 
				[filter setObject:value == nil?@"":value forKey:@"value"];
				if (relField != nil) {
					[filter setObject:[relField objectForKey:@"name"] forKey:@"fld"];
					[filter setObject:fieldName forKey:@"rfld"];
				}
				[queryFilters addObject:filter];
			}	
			rowNum++;
		}
		
		for(int j = 0; j < [queryFilter count]; j++){
			NSMutableDictionary *filter = [queryFilter objectAtIndex:j];
			if ([[filter objectForKey:@"type"] intValue] == 3 || [[filter objectForKey:@"type"] intValue] == 4) {
				NSString *fld = [filter objectForKey:@"fld"];
				[filter setObject:[fld substringToIndex:[fld length] - 4] forKey:@"fld"];
			}
			
			bool flag = YES;
			for(int k = 0; k < [queryFilters count]; k++){
				NSMutableDictionary *filterMap = [queryFilters objectAtIndex:k];
				if([[filterMap objectForKey:@"fld"] isEqualToString:[filter objectForKey:@"fld"]] && 
				   [[filterMap objectForKey:@"type"] isEqualToString:[filter objectForKey:@"type"]]){
					flag = NO;
					break;
				}
			}
			if(flag){
				[queryFilters addObject:filter];
			}
		}
		for(int l = 0; l < [queryFilters count]; l++){
			NSMutableDictionary *map = [queryFilters objectAtIndex:l];
			if(nil == [map objectForKey:@"value"] || [@"" isEqualToString:[map objectForKey:@"value"]]){
				[queryFilters removeObjectAtIndex:l];
				l--;
			}
		}
			
		if (reportDefId == nil) {
			if (queryFirst) {
				if (![[listLayout objectForKey:@"style"] isEqualToString:@"3"]) {
					ListController *listController = [[ListController alloc] init];
					listController.dataObjectName = dataObjectName;
					listController.layoutName = layoutName;
					listController.listLayout = listLayout;
					listController.queryFilter = queryFilters;
					listController.page = 1;
					[self.navigationController pushViewController:listController animated:YES];
					[listController getDataFromServer];
					[listController release];
					
				}
				else {
					AListController *aListController = [[AListController alloc] initWithStyle:UITableViewStylePlain];
					aListController.dataObjectName = dataObjectName;
					aListController.layoutName = layoutName;
					aListController.listLayout = listLayout;
					aListController.queryFilter = queryFilters;
					aListController.page = 1;
					[self.navigationController  pushViewController:aListController animated:YES];
					[aListController getDataFromServer];
					[aListController release];
				}
			}else {
				if (![[listLayout objectForKey:@"style"] isEqualToString:@"3"]) {
					ListController *listController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
					listController.queryFilter = queryFilters;
					listController.page = 1;
					[self.navigationController popViewControllerAnimated:YES];
					[listController getDataFromServer];
				}else {
					AListController *aListController = [self.navigationController.viewControllers objectAtIndex:[self.navigationController.viewControllers count] - 2];
					aListController.queryFilter = queryFilters;
					aListController.page = 1;
					[self.navigationController popViewControllerAnimated:YES];
					[aListController getDataFromServer];
				}
			}
		}else {
			ReportViewController *reportViewController = [[ReportViewController alloc] init];
			reportViewController.reportDefId = [reportDefId retain];
			reportViewController.initialValues = queryFilters;
			[self.navigationController pushViewController:reportViewController animated:YES];
			[reportViewController getDataFromServer];
			[reportViewController release];
		}	
	}
	@catch (NSException * e) {
		[[MCErrorManagement instance] doError:@"99" 
								returnMessage:[NSString stringWithFormat:@"main: Caught %@: %@", [e name], [e reason]]];
	}
}

- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 键盘相关处理

- (void)textFieldDidEndEditing:(UITextField *)textField {
	MCTextField *valueField = (MCTextField*)textField;
	NSMutableDictionary *fieldData = [[formData objectForKey:@"data"] objectForKey:valueField.fieldName];
	[fieldData setObject:valueField.text == nil?@"":valueField.text forKey:@"value"];
	
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
	[super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
	WithFormButtonsBar *withFormButtonsBar = [[WithFormButtonsBar alloc] initWithFrame:CGRectMake(0, 0, self.width, nWithFormButtonsBarHeight)];
	withFormButtonsBar.tag = -8888;
	NSMutableDictionary *queryButton = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"查询",@"lbl",nil];
	NSMutableArray *withButtons = [[NSMutableArray alloc] initWithObjects:queryButton, nil];
	[withFormButtonsBar addWithFormButtons:withButtons buttonCol:1 delegate:self];
	self.tableview.tableFooterView = withFormButtonsBar;
	[withFormButtonsBar release];
}
@end
